package net.vmiranda.jeds.web.files;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ImageFilter
 */
public class ImageFilter extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImageFilter() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	
    protected void process(HttpServletRequest request,HttpServletResponse resp)
    throws ServletException, IOException {
    	//TODO Cachear la imagen!
    	 resp.setContentType("image/jpg");
    	//obtener la ruta solicitada
    	String uri = request.getRequestURI();
    	//la ruta tiene que ser del estilo "/img/caras/victormiranda@gmail.jpg"
    	
    	
    	//con esto tenemos la ruta total de la imagen en el SSFF    	
    	//FIXME PATH
    	String imagePath = GestorFicheros.getDataPath() + uri.replace("/jeds/", "/");
    	
    	File file = new File(imagePath); resp.setContentLength((int)file.length()); // Open the file and output streams
    	FileInputStream in = new FileInputStream(file);
    	OutputStream out = resp.getOutputStream(); // Copy the contents of the file to the output stream 
    	byte[] buf = new byte[1024];
    	int count = 0;
    	while ((count = in.read(buf)) >= 0) {
    		out.write(buf, 0, count); 
    	}
    	in.close();
    	out.close(); 
    	
    }
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {
		process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		process(request, response);
	}

}
